﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging.Messages;
using CommunityToolkit.Mvvm.Messaging;
using Serilog;
using System;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TMI85303.UI.Messages;
using TMI85303.Utils;
using Microsoft.SqlServer.Server;
using System.Windows.Threading;

namespace TMI85303.UI.UserControls
{
    /// <summary>
    /// StatusV1Control.xaml 的交互逻辑
    /// </summary>
    public partial class StatusV1Control : UserControl
    {
        public StatusV1Control()
        {
            InitializeComponent();
        }
    }

    public partial class StatusV1VM : ObservableObject
    {
        [ObservableProperty]
        private SolidColorBrush colorReg147Bit0 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg147Bit1 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg147Bit2 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg147Bit3 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg147Bit4 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg147Bit5 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg147Bit6 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg147Bit7 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg147Bit8 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg147Bit9 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg148Bit0 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg148Bit1 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg148Bit2 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg148Bit3 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg148Bit4 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg148Bit5 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg148Bit6 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg148Bit7 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg148Bit8 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg148Bit9 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg148Bit10 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg148Bit11 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg148Bit12 = ColorsHelper.Green;

        [ObservableProperty]
        private SolidColorBrush colorReg148Bit13 = ColorsHelper.Green;

        [ObservableProperty]
        private double die_temp_C = double.MinValue;

        [ObservableProperty]
        private double die_temp_F = double.MinValue;

        [ObservableProperty]
        private int startTime = 3000;

        [ObservableProperty]
        private int stopTime = 2300;

        [ObservableProperty]
        private int restartSpeed = 500;

        [ObservableProperty]
        private int stepSpeed = 500;

        [ObservableProperty]
        private int maxSpeed = 10000;

        [ObservableProperty]
        private int totalCounts = 5000;

        [ObservableProperty]
        private int residueCounts;

        [ObservableProperty]
        private int reg149_H;

        [ObservableProperty]
        private int reg149_L;

        [ObservableProperty]
        private int reg151;

        [ObservableProperty]
        private int reg152;

        [ObservableProperty]
        private int reg149;

        [ObservableProperty]
        private string startStopContent = "启动";

        [ObservableProperty]
        private string continueReadContent = "持续读取";

        private CancellationTokenSource? tokensource = null; //声明令牌

        private readonly DispatcherTimer continueReadTime = new();

        public StatusV1VM()
        {
            continueReadTime.Interval = TimeSpan.FromSeconds(1);
            continueReadTime.Tick += (s, e) => OnContinueRead();
        }



        [RelayCommand]
        private void ClearDefault()
        {
            ReadWrite.WriteReg(148, 0x8000, 2);
            ReadWrite.WriteReg(148, 0, 2);
            GetFaults();
        }

        [RelayCommand]
        private void ReadReg138_147_148()
        {
            int readData138 = ReadWrite.ReadReg(138, 2);
            double degC = 3.0 + (readData138 - 133.0) / 2;
            double degF = 1.8 * (double)degC + 32.0;
            Die_temp_C = Math.Round(degC, 1);
            Die_temp_F = Math.Round(degF, 1);
            GetFaults();
        }

        private int onoffCount = 0;

        [RelayCommand]
        private void StartStop(object parameter)
        {
            if (parameter is not bool isChecked) return;

            if (isChecked)
            {
                StartStopContent = "停止";
                ResidueCounts = TotalCounts;
                faultsCounts = 0;
                onoffCount = 0;

                tokensource = new CancellationTokenSource();
                var cancellationToken = tokensource.Token;
                Task.Run(() =>
                {
                    int _startTime = StartTime;
                    int _stopTime = StopTime;
                    int _totalCounts = TotalCounts;
                    int _residueCounts = 0;
                    int _restartSpeed = RestartSpeed;
                    int _stepSpeed = StepSpeed;
                    int _maxSpeed = MaxSpeed;

                    do
                    {
                        if (cancellationToken.IsCancellationRequested) break;

                        if (_restartSpeed < _maxSpeed)
                        {
                            if (ReadWrite.ReadReg(140, 2) <= _restartSpeed)
                            {
                                ReadWrite.WriteReg(165, 511, 2);
                                Thread.Sleep(_startTime);
                                ReadWrite.WriteReg(165, 0, 2);
                                //Thread.Sleep(stopTime);
                                GetFaults();

                                onoffCount++;
                                _residueCounts = _totalCounts - onoffCount;
                                Application.Current.Dispatcher.Invoke(() => ResidueCounts = _residueCounts);
                                _restartSpeed += _stepSpeed;
                                Application.Current.Dispatcher.Invoke(() => RestartSpeed = _restartSpeed);
                            }
                        }
                        else
                        {
                            while ((_restartSpeed > _stepSpeed) && (onoffCount < _totalCounts))
                            {
                                if (ReadWrite.ReadReg(140, 2) < _restartSpeed)
                                {
                                    ReadWrite.WriteReg(165, 511, 2);
                                    Thread.Sleep(_startTime);
                                    ReadWrite.WriteReg(165, 0, 2);
                                    //Thread.Sleep(stopTime);
                                    GetFaults();

                                    onoffCount++;
                                    _residueCounts = _totalCounts - onoffCount;
                                    Application.Current.Dispatcher.Invoke(() => ResidueCounts = _residueCounts);
                                    _restartSpeed -= _stepSpeed;
                                    Application.Current.Dispatcher.Invoke(() => RestartSpeed = _restartSpeed);
                                }

                                Thread.Sleep(100);
                            }
                        }

                        Thread.Sleep(100);
                    }
                    while (onoffCount < _totalCounts);

                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        StartStopContent = "启动";
                        ResidueCounts = 0;
                    });

                }, cancellationToken);
            }
            else
            {
                tokensource?.Cancel();
                ReadWrite.WriteReg(165, 0, 2);
            }
        }

        [RelayCommand]
        private void ReadReg149_151_152()
        {
            Reg151 = ReadWrite.ReadReg(151, 2);
            Reg152 = ReadWrite.ReadReg(152, 2);

            int _reg149 = ReadWrite.ReadReg(149, 2);
            Reg149 = _reg149;
            Reg149_H = (_reg149 >> 4) & 7;
            Reg149_L = _reg149 & 0xF;
        }

        [RelayCommand]
        private void ContinueReadReg149_151_152(object parameter)
        {
            if (parameter is not bool isChecked) return;
            if (isChecked)
            {
                ContinueReadContent = "停止读取";
                continueReadTime.Start();
            }
            else
            {
                ContinueReadContent = "持续读取";
                continueReadTime.Stop();
            }
        }

        private void OnContinueRead()
        {
            Reg151 = ReadWrite.ReadReg(151, 2);
            Reg152 = ReadWrite.ReadReg(152, 2);

            int _reg149 = ReadWrite.ReadReg(149, 2);
            Reg149 = _reg149;
            Reg149_H = (_reg149 >> 4) & 7;
            Reg149_L = _reg149 & 0xF;
        }

        private int faultsCounts = 0;
        private void GetFaults()
        {
            faultsCounts++;

            int data147 = ReadWrite.ReadReg(147, 2);
            int data148 = ReadWrite.ReadReg(148, 2);
            if ((data147 != 0) || (data148 != 0))
            {
                //int speed = ReadWrite.ReadReg(140, 2);

                Saveport.saveFault_speed("Faults" + faultsCounts.ToString(), RestartSpeed.ToString("X4"));
                Saveport.saveFault_147("Faults" + faultsCounts.ToString(), data147.ToString("X4"));
                Saveport.saveFault_148("Faults" + faultsCounts.ToString(), data148.ToString("X4"));

                //ReadWrite.WriteReg(148, 0x8000, 2);
                //ReadWrite.WriteReg(148, 0, 2);
            }
            ColorReg147Bit0 = ((data147 & 1) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg147Bit1 = ((data147 & 2) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg147Bit2 = ((data147 & 4) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg147Bit3 = ((data147 & 8) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg147Bit4 = ((data147 & 0x10) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg147Bit5 = ((data147 & 0x20) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg147Bit6 = ((data147 & 0x40) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg147Bit7 = ((data147 & 0x80) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg147Bit8 = ((data147 & 0x100) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg147Bit9 = ((data147 & 0x200) == 0) ? ColorsHelper.Green : ColorsHelper.Red;

            ColorReg148Bit0 = ((data148 & 1) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg148Bit1 = ((data148 & 2) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg148Bit2 = ((data148 & 4) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg148Bit3 = ((data148 & 8) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg148Bit4 = ((data148 & 0x10) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg148Bit5 = ((data148 & 0x20) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg148Bit6 = ((data148 & 0x40) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg148Bit7 = ((data148 & 0x80) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg148Bit8 = ((data148 & 0x100) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg148Bit9 = ((data148 & 0x200) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg148Bit10 = ((data148 & 0x400) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg148Bit11 = ((data148 & 0x800) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg148Bit12 = ((data148 & 0x1000) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
            ColorReg148Bit13 = ((data148 & 0x2000) == 0) ? ColorsHelper.Green : ColorsHelper.Red;
        }

    }
}
